package game.module.qzmj.processor;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import game.HallServer;
import game.common.ErrorCodeConstants;
import game.common.PlayingRoleMsgProcessor;
import game.entity.PlayingRole;
import game.module.hall.logic.CheatManager;
import game.module.offline.bean.PlayerOfflineCache;
import game.module.offline.logic.PlayerOfflineManager;
import game.module.qzmj.bean.QzmjRoom;
import game.module.qzmj.logic.QzmjDataManager;
import game.module.qzmj.logic.QzmjLogic;
import game.session.SessionManager;
import game.util.CommUtil;
import lion.common.MsgCodeAnn;
import lion.netty4.message.MyRequestMessage;
import lion.netty4.message.RequestMessageRaw;
import lion.netty4.message.RequestProtoMessage;
import lua.LuaMessageLogin.S2ErrorCode;
import lua.LuaMessageQzmj.C2SQzmjJoinRoom;
import lua.LuaMessageQzmj.PushQzmjPlayerJoin;
import lua.LuaMessageQzmj.QzmjMemberInfo;
import lua.LuaMessageQzmj.S2CQzmjJoinRoom;

@MsgCodeAnn(msgcode = C2SQzmjJoinRoom.id, accessLimit = 500)
public class QzmjJoinRoomProcessor extends PlayingRoleMsgProcessor {

	private static Logger logger = LoggerFactory.getLogger(QzmjJoinRoomProcessor.class);

	@Override
	public void process(PlayingRole hero, RequestMessageRaw request) throws Exception {
		// TODO Auto-generated method stub
		C2SQzmjJoinRoom reqMsg = C2SQzmjJoinRoom.parse(request);
		String room_id = reqMsg.room_id;
		int playerId = hero.getId();
		logger.info("qzmj join room,playeyId={},room_id={}", playerId, room_id);

		// 是否在房间
		boolean isInRoom = QzmjDataManager.getInstance().isPlayerInRoom(playerId);
		if (isInRoom) {
			S2ErrorCode respMsg = new S2ErrorCode(102);
			hero.writeAndFlush(respMsg.build(hero.alloc()));
			return;
		}
		// is fang not exist
		if (!QzmjDataManager.getInstance().checkRoomExist(room_id)) {
			S2ErrorCode respMsg = new S2ErrorCode(104);
			hero.writeAndFlush(respMsg.build(hero.alloc()));
			return;
		}

		final QzmjRoom mjRoom = QzmjDataManager.getInstance().getMjRoom(room_id);
		//
		int fangka = hero.getPlayerBean().getFang_ka();
		int fangka_cost = mjRoom.getFee();
		if (mjRoom.getCost_type() == 2 && fangka < fangka_cost)// 赢家收费
		{
			S2ErrorCode respMsg = new S2ErrorCode(103);
			hero.writeAndFlush(respMsg.build(hero.alloc()));
			return;
		}
		if (mjRoom.getCost_type() == 1 && fangka < fangka_cost / 2) {// AA
			S2ErrorCode respMsg = new S2ErrorCode(103);
			hero.writeAndFlush(respMsg.build(hero.alloc()));
			return;
		}

		// 人数满了
		if (mjRoom.getPlayerList().size() >= 4) {
			S2ErrorCode respMsg = new S2ErrorCode(105);
			hero.writeAndFlush(respMsg.build(hero.alloc()));
			return;
		}

		CheatManager.getInstance().checkCheatAndJoin(mjRoom.getPrevent_cheat(), mjRoom.getIps(), hero);
        Map<Integer,String> ipmaps = mjRoom.getIpmaps();
        ipmaps.put(playerId, CommUtil.getIpAddr(hero.getGamePlayer().getAddress()));
        
		QzmjLogic.getInstance().addRoomPlayer(playerId, room_id);
		S2CQzmjJoinRoom respMsg = new S2CQzmjJoinRoom();
		respMsg.room_id = room_id;
		respMsg.round_count = mjRoom.getRoundCount();
		respMsg.sanjindao = mjRoom.getSanjindao();
		respMsg.eat_card = mjRoom.getEat_card();
		respMsg.hua_card = mjRoom.getHua_card();
		respMsg.prevent_cheat = mjRoom.getPrevent_cheat();
		respMsg.gold_rate = mjRoom.getGold_coin();
		respMsg.cost_type = mjRoom.getCost_type();
		respMsg.youjin = mjRoom.getYoujin();
		respMsg.ready = mjRoom.getReady();
		respMsg.members = new QzmjMemberInfo[mjRoom.getPlayerList().size()];
		List<Integer> playerIdList = mjRoom.getPlayerList();
		int i = 0;
		for (Integer aPlayerId : playerIdList) {
			PlayerOfflineCache poc = PlayerOfflineManager.getInstance().getPlayerOfflineCache(aPlayerId);
			Long jindou = poc.getJindou();
			int showJd = jindou != null ? jindou.intValue() : 0;
			respMsg.members[i++] = new QzmjMemberInfo(aPlayerId, poc.getHeadimg(), poc.getLevel(), poc.getSex().shortValue(), showJd, hero.getGamePlayer().getAddress(),poc.getName());
		}
		hero.writeAndFlush(respMsg.build(hero.alloc()));
		QzmjDataManager.getInstance().addPlayer(playerId, room_id);
		PushQzmjPlayerJoin pushMsg = new PushQzmjPlayerJoin();
		pushMsg.seat_index = (short) (mjRoom.getPlayerList().size() - 1);
		long jindou = hero.getPlayerBean().getJin_dou();
		pushMsg.member_info = new QzmjMemberInfo(playerId, hero.getPlayerBean().getHeadimg(), hero.getPlayerBean().getLevel(), hero.getPlayerBean().getSex().shortValue(),
				(int) jindou,ipmaps.get(playerId), hero.getPlayerBean().getName());
		for (Integer aPlayerId : playerIdList) {
			if (aPlayerId == playerId) {
				continue;
			}
			PlayingRole pr = SessionManager.getInstance().getPlayer(aPlayerId);
			if (pr != null && pr.isChannelActive()) {
				pr.writeAndFlush(pushMsg.build(pr.alloc()));
			}
		}
		// delay 2 seconds to start
		// HallServer.executorService.schedule(new Runnable() {
		//
		// @Override
		// public void run() {
		// if (MjRoom.getPlayerList().size() >= 4) {
		// sendRoomStart(MjRoom);
		// }
		// }
		// }, 2, TimeUnit.SECONDS);
	}

	private void sendRoomStart(QzmjRoom mjRoom) {
		logger.info("qzmj start battle!");
		String rsLanHost = HallServer.getInstance().getServerConfig().getRsLanHost();
		int rsLanPort = HallServer.getInstance().getServerConfig().getRsLanPort();
		boolean reconnectRet = HallServer.getInstance().getLanClientManager().connect(rsLanHost, rsLanPort);
		if (reconnectRet) {
			HallServer.getInstance().getLanClientManager().sendQzmjStart2Rs(rsLanHost, rsLanPort, mjRoom);
		} else {
			logger.error("connect 2 roomServer error!rsLanHost={},rsLanPort={}", rsLanHost, rsLanPort);
		}
	}

	@Override
	public void processProto(PlayingRole playingRole, RequestProtoMessage request) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void processWebsocket(PlayingRole playingRole, MyRequestMessage request) throws Exception {
		// TODO Auto-generated method stub

	}

}
